/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package systole.view.wizard;

import javax.swing.JOptionPane;
import systole.view.messages.DialogsMessages;

/**
 *
 * @author jmj
 */
public abstract class WizardImplement {

    protected WizardSequenceController sequenceController;
    protected StepsController stepsController;
    protected WizardView view;
    protected PageController currentPage;
    protected WizardResult result;

    public WizardImplement(java.awt.Frame parent) {
        this.view = new WizardView(parent, this);
        this.view.setLocationRelativeTo(parent);
    }

    public Object executeWizard() {
        this.initWizard();
        this.currentPage = this.sequenceController.startSequence();
        this.stepsController.setAsCurrentPage(this.currentPage);
        this.view.setVisible(true);
        return (this.result != null ? this.result.generateResult() : null);
    }

    protected abstract void initWizard();

    public void finish() {
         String error = this.currentPage.validatePage();
        if (error == null) {
            this.stepsController.markAsDone(currentPage);
            this.result = this.currentPage.loadResult(this.result);
            this.view.setVisible(false);
        } else {
            JOptionPane.showOptionDialog(this.view,
                    error, DialogsMessages.DIALOG_BOX_TITLE,
                    JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE, null,
                    null, null);
        }
    }

    public void cancel() {
        if (JOptionPane.showOptionDialog(this.view,
                "¿Desea cerrar el Wizard?", DialogsMessages.DIALOG_BOX_TITLE,
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                null, null) == JOptionPane.OK_OPTION) {
            this.view.setVisible(false);
            this.result = null;
            this.view.dispose();
        }
    }

    public void nextPage() {
        String error = this.currentPage.validatePage();
        if (error == null) {
            this.stepsController.markAsDone(currentPage);
            this.result = this.currentPage.loadResult(this.result);
            this.currentPage = this.sequenceController.nextPage();
            this.stepsController.setAsCurrentPage(this.currentPage);
            this.currentPage.setPreviousStepData(this.result);
        } else {
            JOptionPane.showOptionDialog(this.view,
                    error, DialogsMessages.DIALOG_BOX_TITLE,
                    JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE, null,
                    null, null);
        }
    }

    public void previousPage() {
        this.stepsController.markAsUndo(currentPage);
        this.currentPage = this.sequenceController.previousPage();
        this.stepsController.setAsCurrentPage(this.currentPage);
    }
}
